<?php
class AdminUtil
{
	public static function clearTemplateCache($type='all')
	{
		$cacheDir = substr(dirname(__FILE__), 0, strrpos(__FILE__, "lib")).'tmp/';
		$clearDirName = 'templateView';
		if($type!='all')
		{
			$cacheDir .= 'templateView/';
			$clearDirName = $type;
		}
		
		if(!is_dir($cacheDir.$clearDirName))
		{
			return true;
		}
		
		$time = time();
		if(!rename($cacheDir.$clearDirName,$cacheDir.$clearDirName.$time) && !is_dir($cacheDir.$clearDirName.$time))
		{
			return false;
		}
		else
		{
			return self::rmdir($cacheDir.$clearDirName.$time);
		}
	}
	
	public static function rmdir($dir)
	{
		if (!file_exists($dir))
		{
			return true;
		}
		if ((!is_dir($dir) || is_link($dir)))
		{
			return unlink($dir);
		}
		$dirs = Util::getDirFiles($dir);
		foreach($dirs as $item)
		{
			if ($item == '.' || $item == '..')
			{
				continue;
			}
			if (!self::rmdir($dir .DIRECTORY_SEPARATOR . $item))
			{
				if (!self::rmdir($dir . DIRECTORY_SEPARATOR . $item))
				{
					return false;
				}
			};
		}
		return rmdir($dir);
	}
	
	public static function getTemplates()
	{
		$templates		= array();
		$templateDir	= substr(dirname(__FILE__), 0, strrpos(__FILE__, "lib")).'view/frontend/';
		$dirs			 = Util::getDirFiles($templateDir);
		foreach($dirs as $item)
		{
			if (strpos($item,'.')===0 || !is_dir($templateDir.$dir))
			{
				continue;
			}
				
			$templates[]	= $item;
		}
		
		return $templates;
	}
	
	public static function getAdPositions()
	{
		$templates = self::getTemplates();
		$adPositionService = new BaseDbService('ad_position');
		$adPositions = $adPositionService->rows(array(),'id ASC');
		
		$list = array();
		foreach($templates as $template)
		{
			$list[] = array('id'=>'tv_'.$template, 'name'=>$template, 'value'=>'tv_'.$template, 'pid'=>0);
		}
		foreach($adPositions as $adPosition)
		{
			$list[] = array('id'=>$adPosition['id'],'name'=>$adPosition['name'],'value'=>$adPosition['id'],'pid'=>'tv_'.$adPosition['template']);
		}
		
		$all = array();
		$multi = array();
		foreach($list as $cv)
		{
			$tmp							= array('name'=>$cv['name'],'value'=>$cv['id'],'pid'=>$cv['pid']);
			$all[$cv['id']]					= $tmp;
			$multi['multi_'.$cv['pid']][]	= $tmp;
		}
	
		return array('dataAllCategory'=>$all,'dataMultiCategory'=>$multi);
	}
	
	public static function clearAdCache()
	{
		C('LtCache')->del('system');
	}
}
?>